package com.qf.fmall.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 在springboot2中写一个统计所有添加了@Service注解的类的方法的运行时长的切面
 */
@Aspect
@Component
public class TimeAspect {

//    @Before("@annotation(org.springframework.web.bind.annotation.GetMapping)")

//    @Before("execution(* com.qf..*Impl.*(..))")
//    @Before("execution(* com.qf..*Ser*.*(..))")
//    @Before("execution(* com.qf.fmall.index..*.*()) && @annotation(org.springframework.web.bind.annotation.GetMapping)")
    @Before("@within(org.springframework.web.bind.annotation.RestController)")
    public void before(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        System.out.println("=======>");
        System.out.println(signature);
        Object[] args = joinPoint.getArgs();
        if (args.length>0){
            for (Object arg : args) {
                System.out.println(arg);
            }
        }
        System.out.println("=======>");
    }



    @Around("@within(org.springframework.stereotype.Service)")
    public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;

        // 打印方法运行时长
        System.out.println(joinPoint.getSignature() + " 执行时长：" + executionTime + "ms");

        return result;
    }

}
